import React, { useEffect } from 'react';
import { Button, Form, Input, Select, DatePicker, message } from 'antd';
import { post } from '../../components/axios';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';

const NewProject = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();

  // 自动生成项目编号和合同编号
  useEffect(() => {
    form.setFieldsValue({
      projectNumber: 'P' + Date.now(),
      contractNumber: 'C' + Date.now()
    });
  }, [form]);

  // 校验：结束时间不能小于开始时间，开始/结束时间不能小于今天
  const validateStartTime = (_, value) => {
    if (!value) return Promise.resolve();
    if (value.isBefore(dayjs().startOf('day'))) {
      return Promise.reject('开始时间不能小于今天');
    }
    return Promise.resolve();
  };
  const validateEndTime = (_, value) => {
    const startTime = form.getFieldValue('projectStartDate');
    if (!value) return Promise.resolve();
    if (value.isBefore(dayjs().startOf('day'))) {
      return Promise.reject('结束时间不能小于今天');
    }
    if (startTime && value.isBefore(startTime, 'day')) {
      return Promise.reject('结束时间不能小于开始时间');
    }
    return Promise.resolve();
  };

  const onFinish = (values) => {
    // 计算项目周期天数
    const startDate = values.projectStartDate ? dayjs(values.projectStartDate) : null;
    const endDate = values.projectEndDate ? dayjs(values.projectEndDate) : null;
    const durationDays = startDate && endDate ? endDate.diff(startDate, 'day') + 1 : 0;

    const data = {
      ...values,
      status: '未开始',
      progress: '0%',
      projectStartDate: values.projectStartDate ? values.projectStartDate.format('YYYY-MM-DD') : '',
      projectEndDate: values.projectEndDate ? values.projectEndDate.format('YYYY-MM-DD') : '',
      durationDays: durationDays,
      creationTime: new Date().toISOString(),
      updateTime: new Date().toISOString()
    };

    console.log('提交的数据:', data);

    post('/projectlist/add', data).then(res => {
      console.log('完整响应:', res);
      console.log('接口返回:', res.data);
      const code = res?.data?.code ?? res?.code;
      if (code === 200 || code === '200') {
        message.success('保存成功!');
        setTimeout(() => {
          navigate('/projects/projectlist', { 
            state: { 
              refresh: true,
              newProject: res.data.data 
            } 
          });
        }, 800);
      } else {
        message.error(res?.data?.msg || res?.msg || '保存失败');
      }
    }).catch(err => {
      message.error('请求失败');
      console.error('保存出错:', err);
    });
  };

  return (
    <div style={{ backgroundColor: '#f7f7f7', minHeight: '100vh' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '0px 50px' }}>
        <h3>新建项目</h3>
      </div>
      <hr style={{ border: '2px solid #e0e3ea', height: '0' }} />
      <div
        style={{
          width: '70%',
          backgroundColor: 'white',
          margin: '20px auto',
          padding: '20px 40px',
          borderRadius: '5px',
          flexGrow: 1,
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'flex-start',
          marginTop: "-5px"
        }}
      >
        <h4 style={{ marginBottom: '20px' }}>基础信息</h4>
        <hr style={{ border: '1px dashed #ccc', margin: '5px 0' }} />
        <div style={{ flexGrow: 1 }}>
          <Form
            form={form}
            layout="horizontal"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            style={{ maxWidth: '100%' }}
            onFinish={onFinish}
            onFinishFailed={(err) => { console.log('表单校验失败', err); }}
          >
            <Form.Item label="项目编号：" name="projectNumber" rules={[{ required: true, message: '请输入项目编号' }]}>
              <Input disabled />
            </Form.Item>
            <Form.Item label="项目类型：" name="projectType" rules={[{ required: true, message: '请选择项目类型' }]}>
              <Select placeholder="请选择" allowClear showSearch={false} open={undefined}>
                <Select.Option value="外包">外包</Select.Option>
                <Select.Option value="Outsourcing">Outsourcing</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item label="项目名称：" name="projectName" rules={[{ required: true, message: '请输入项目名称' }]}>
              <Input placeholder="请输入" />
            </Form.Item>
            <Form.Item label="关联客户：" name="relatedClient" rules={[{ required: true, message: '请选择关联客户' }]}>
              <Input placeholder="请输入" />
            </Form.Item>
            <Form.Item label="合同编号：" name="contractNumber" rules={[{ required: true, message: '请输入合同编号' }]}>
              <Input disabled />
            </Form.Item>
            <Form.Item label="签约人：" name="signatory" rules={[{ required: true, message: '请输入签约人' }]}>
              <Input placeholder="请输入" />
            </Form.Item>
            <Form.Item label="项目分类：" name="projectCategory">
              <Input placeholder="请输入" />
            </Form.Item>
            <Form.Item label="项目开始时间：" name="projectStartDate" rules={[{ required: true, message: '请选择项目开始时间' }, { validator: validateStartTime }]}>
              <DatePicker style={{ width: '100%' }} placeholder="请选择" inputReadOnly />
            </Form.Item>
            <Form.Item label="项目结束时间：" name="projectEndDate" rules={[{ required: true, message: '请选择项目结束时间' }, { validator: validateEndTime }]}>
              <DatePicker style={{ width: '100%' }} placeholder="请选择" inputReadOnly />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" style={{ marginRight: '10px', backgroundColor: '#e5a452', color: 'white' }}>保存</Button>
              <Button onClick={() => navigate('/projects/projectlist')}>取消</Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    </div>
  );
};

export default NewProject;